
import logging
import requests
from email.mime.text import MIMEText

dingding_url = "https://oapi.dingtalk.com/robot/send?access_token=387fe60575cb1a2eaab0e4cdd25f46e9896c1963d0bd026af8069e84fe6dac27"


def send(process=None, subject_format='{executable} process {pid} ended'):
    """Send dingding about the ended process.

    :param to: email addresses to send to
    :param process: information about process. (.info() inserted into body)
    :param subject_format: subject format string. (uses process.__dict__)
    """
    body = " 进程消息:" + process.info()
    body += '\n\n(automatically sent by process-watcher program)'
    msg = {"msgtype": "text", "text": {"content": body}}
    subject = subject_format.format(**process.__dict__)
    body = subject + body
    try:
        logging.info('Sending dingding msg')
        r = requests.post(dingding_url, json=msg)
    except Exception as e:
        r = -1
        logging.exception(e)
    logging.info(r)
